<?php
require_once("functions.php");
require_once("security.class.php");
require_once("db_functions.php");

define(MAX_SEARCH_LIST,50);
define(PAGE_LENGTH,30);
define(DAY,60*60*24);

/**
 * Glavna klasa prikaza strane
 * @author Voislav Jovanović - voislavj@gmail.com
 *
 */
class page extends security{
	var $user_level;
	var $html;
	
	// config array delimiter
	var $configArrayDelimiter = "{!}";
	//array u kome se skupljaju razne promenljive i drugi arrayi
	var $_arej;
	//string u kojem je adresa do templates direktorijuma
	var $_templates = "templates";
	//associative array u kome je config uchitan
	var $_configArej;
	//array count
	var $_arrcount;
	//array counter
	var $_arrcounter;
	//array u koji se smesta ceo template
	var $tmpArray;
	//pocetak loop-a
	var $loopstart;
	//duzina loop-a
	var $cyclenum;
	//loop counter
	var $loopcount;
	//output string
	var $output;
	//da li je prazan loop
	var $emptyloop;
	
	var $_container;
	
	var $db;


	function page($template="main.tpl"){
		$this->initPage();		
		if($this->isUserLoggedIn()){
			$this->db = new db_functions();
			$q = "SELECT users.username, radnici.radnik_ime, radnici.radnik_prezime, users.last_login, groups.gname "
				."FROM radnici, users,groups "
				."WHERE users.gid=groups.gid "
				."AND radnici.radnik_id=users.radnik_id "
				."AND users.id='".$_COOKIE['ypu']."'";
			$res = $this->db->getRow($q);
			
			$this->assign("user",$res[0]);
			$this->assign("user_ime",$res[1]);
			$this->assign("user_prezime",$res[2]);
			$this->assign("user_last_login",date($this->getFromConfig("long_date"),$res[3]));
			$this->assign("user_level",$res[4]);
			$this->user_level = $res[4];
			$this->assign("ip_address",$_SERVER['REMOTE_ADDR']);
			
			$group = strtolower($res[4]);
			$menu_tpl = "mmenu/".preg_replace('/[^a-z]/',"",$group).".tpl";
			$home_tpl = "home/".preg_replace('/[^a-z]/',"",$group).".tpl";
			
			if (file_exists($this->_templates."/".$home_tpl)) {
				$shortcut_html = $this->parseTemplate($home_tpl);
				$this->assign("shortcut",$shortcut_html);
			}
			
			$onload = getFromInput("func");
			if(strlen($onload)){
				$onload = stripslashes($onload);
				$this->assign("onloadScripts","<script>$onload</script>");
			}
			
			if (!$this->isSuperUser($_COOKIE["ypu"],$this->user_level)) {
				$this->assign("super_user_start","<!--");
				$this->assign("super_user_end","-->");
			}
			
			$this->assign("main_menu",$this->parseTemplate($menu_tpl));
			$this->_container = $template;
		}else{
			$this->_container = "login.tpl";
		}
	}
	function isSuperUser($userid,$userlevel){
		$superUsers = array(
			"admin2",	// voja
			"admin9",	// zarko
			"admin4",	// dubravka
			"admin6"	// jasmina dimitrov
		);
		if (in_array($userlevel.$userid,$superUsers,true)) {
			return true;
		}else{
			return false;
		}
	}
	function initPage(){
		$this->loadConfig();
		$this->loadOptions();
	}
	function loadConfig($conf = "cfg/config.cfg"){
		if (file_exists($conf)) {
			$f = file($conf);
			$first = true;
			foreach($f as $line){
				if($first){
					$first = false;
					continue;
				}
				if((substr($line,0,1) != "#") && (strlen(trim($line)) > 0)){
					$line = trim($line);
					$trimmed = explode("=",$line);
					$var_name = trim($trimmed[0]);
					$var_value = trim($trimmed[1]);
					if(preg_match('/'.$this->configArrayDelimiter.'/',$var_value)){
						$tmp = explode($this->configArrayDelimiter,$var_value);
						foreach($tmp as $k=>$v){
							$arr[$k]=$v;
						}
						$var_value = $arr;
					}
					$this->_configArej[$var_name] = $var_value;
				}
			}
			return true;
		}else{
			return false;
		}
	}
	function loadOptions(){
		$desktop_logo = isset($_COOKIE["desktop_logo"])?$_COOKIE["desktop_logo"]:false;
		if(!$desktop_logo)
			$desktop_logo=0;
		if($desktop_logo){
			$this->assign("container_style","style=\"background:url(gui/body_logo.png) no-repeat 97% 97%;\"");
			$this->assign("options",'<li><a href="javascript:void(0)" class="checked" onclick="toggleOption(this,\'desktop_logo\');">Desktop logo</a></li>');
		}else{
			$this->assign("container_style","style=\"\"");
			$this->assign("options",'<li><a href="javascript:void(0)" onclick="toggleOption(this,\'desktop_logo\');">Desktop logo</a></li>');
		}
	}
	function getFromConfig($var){
		if (!count($this->_configArej)) {
			$this->loadConfig();
		}
		return $this->_configArej[$var];
	}
	function assign($ime,$vrednost){
		if (is_numeric($vrednost)) {
			$vrednost = sprintf("%s",$vrednost);
		}
		$this->_arej[$ime] = $vrednost;
		return true;
	}
	function displayPage(){
		$this->assign("container",$this->parseTemplate($this->_container));
		$js_dir = opendir("js");
		$scripts = "\r\n<!-- javascript -->\r\n";
		while ($f = readdir($js_dir)) {
			if(preg_match('/\.js$/',$f) && !preg_match('/^!/',$f)){
				$scripts .= '<script type="text/javascript" language="javascript" src="js/'.$f.'"></script>'."\r\n";
			}
		}
		
		$this->assign("scripts",$scripts);
		$this->html = $this->parseTemplate("gui.tpl");
		echo $this->html;
	}
	function parseTemplate($templateName,$slice = "/{{(.*?)}}/is"){
		$this->loadColors();
		$this->tmpArray = $this->getTemplate($templateName);
		$output = @implode ("", $this->tmpArray);
		$this->tmpArray = preg_split($slice, $output, -1, PREG_SPLIT_DELIM_CAPTURE);
		$this->_arrcount = count($this->tmpArray);
		$this->_arrcounter = 0;
		$output = "";
		while ($this->_arrcounter < $this->_arrcount) {
			$linija = trim ($this->tmpArray[$this->_arrcounter]);
			$out = $this->isTag($linija);
			if (strlen($out)>0) {
				if ($this->emptyloop) {
					$out = " ";
				}
				if ($out == "{EMPTY}") {
					$out = "";
				}
				$output .= $out;
			}elseif (!$this->emptyloop){
				$output .= $linija;
			}
			$this->_arrcounter ++;
		}
		return $output;
	}
	function getTemplate($name){
		return @file($this->_templates."/".$name);
	}
	function loadStyles($ret=true){
		$cssdir = "css";
		
		$dir = opendir($cssdir);
		$out = "";
		while ($f = readdir($dir)) {
			if (preg_match('/^[^!].*?\.css/',$f)) {
				$out .= '<link rel="stylesheet" href="'.$cssdir.'/'.$f.'" />'."\r\n";
			}
		}
		if ($ret) {
			return $out;
		}else{
			echo "$out";
		}
	}
	function loadColors($filename="css/colors.cfg"){
		$var = file_exists($filename)?"1":"0";
		if (file_exists($filename)) {
			$file = file($filename);
			foreach ($file as $line){
				if(!preg_match('/^#/',$line) && preg_match('/=/',$line)){
					$tmp = explode("=",trim($line),2);
					$this->assign(trim($tmp[0]),trim($tmp[1]));
				}
			}
		}
		$this->assign("nema_fajla","");
	}
	function isTag($lin){
		switch(substr($lin,0,1)){
			case "#": // rad sa configom
				$tempout = substr(strrchr ($lin, "#"), 1);
				$return = $this->getFromConfig($tempout);
				break;
			case "$": // rad sa promenljivama
				$tempout = substr(strrchr ($lin, "$"), 1);
				if (isset($this->_arej[$tempout]) && is_array($this->_arej[$tempout])){
					if ($this->_arej[$tempout][$this->loopcount] != NULL) {
						$return = $this->_arej[$tempout][$this->loopcount];
					}else{
						$return = "{EMPTY}";
					}
				}else{
					if (isset($this->_arej[$tempout]) && $this->_arej[$tempout] != "") {
						//if($this->_arej[$tempout] !=)
						$return = $this->_arej[$tempout];
					}else{
						$return = "{EMPTY}";
					}
				}
				break;
			case "%": // rad sa funkcijama
				$tempout = substr(strrchr ($lin, "%"), 1);
				$return = $this->callFunction($tempout);
				break;
			default: // ostalo
				$return = false;
				break;
		}
		return $return;
	}
	function callFunction ($linija){
		$cmdstr = explode(" ", $linija);
		$prvi = true;
		foreach ($cmdstr as $deo) {
			if ($deo != "") {
				if ($prvi) {
					$komanda = $deo;
					$prvi = false;
				}else{
					$parametri[] = $deo;
				}
			}
		}
		switch ($komanda) {
			case "loop":
				return $this->loop($parametri);
				break;
			case "loopnum":
				return $this->loopnum($parametri);
				break;
			case "config":
				return $this->addConfig($parametri);
				break;
			case "random":
				return $this->random();
				break;
			default:
				return " ";
		}
	}
	function loop($param) {
		$out = "";
		if ($param[0] == "start") {
			$this->loopstart = ($this->getCounter());
			$this->cyclenum = count($this->_arej[$param[1]]);
			$this->loopcount = 0;
			if (!$this->cyclenum) {
				$this->emptyloop = true;
			}
			return " ";
		}
		if ($param[0] == "end") {
			$this->emptyloop = false;
			$this->loopcount ++;
			if ($this->loopcount < $this->cyclenum) {
				$this->_arrcounter = $this->loopstart;
			}
			return " ";
		}
		return false;
	}
	function loopnum(){
		return $this->loopcount + 1;
	}
	function getCount() {
		return $this->_arrcount;
	}
	function getCounter() {
		return $this->_arrcounter;
	}
	function generateLetters(){
		$this->loadConfig();
		$letts = $this->getFromConfig('slova_filter');
		$this->assign("slova",$letts);
	}
	function currentFilter($filter){
		echo "<script>setCurrentLetterFilter('".$filter."')</script>";
	}
	

//-------------------------------------------------------------------------------------------
//				GET METHODS
//-------------------------------------------------------------------------------------------
	
	
	
	function getUserLevel(){
		$u = $_COOKIE["ypu"];
		$q = "SELECT groups.gid,groups.gname FROM users, groups WHERE users.id=$u AND users.gid=groups.gid";
		$res = $this->db->getRow($q);
		
		$q = "SELECT * FROM group_rights WHERE `group`=".$res[0]." LIMIT 1";
		$rights = $this->db->getRow($q,true);
		unset($rights["group"]);
		$ret["id"] = $res[0];
		$ret["name"] = $res[1];
		$ret["rights"] = $rights;
		return $ret;
	}
	/**
	 * Preuzimanje svih regiona
	 *
	 * @return Array(region_id,region_name)
	 */
	function get_Regioni($regid=null){
		$ret = array();
		$q = "SELECT region_id, region_name FROM regioni ORDER BY region_name";
		$res= $this->db->select2($q);
		if(count($res)>0){
			foreach($res as $key_res=>$val_res){
				$res['polje_id'][$key_res]=$val_res["region_id"];
				$res['polje_ime'][$key_res]=$val_res["region_name"];
				if($regid == $val_res["region_id"]){
					$res["polje_selected"][$key_res] = " selected";
				}else{
					$res["polje_selected"][$key_res] = "";
				}
			}
		}
		return $res;
	}
	/**
	 * Preuzimanje svih opstina
	 *
	 * @return Array(opstina_id,opstina_name,opstina_parent)
	 */
	function get_Opstine($opsid=null){
		$ret = array();
		$q = "SELECT * FROM opstine ORDER BY opstina_name";
		$res= $this->db->select2($q);
		if(count($res)>0){
			foreach($res as $key_res=>$val_res){
				$res['polje_id'][$key_res]=$val_res["opstina_id"];
				$res['polje_ime'][$key_res]=$val_res["opstina_name"];
				$res['polje_parent'][$key_res]=$val_res["opstina_region_id"];
				if($opsid == $val_res["opstina_id"]){
					$res["polje_selected"][$key_res] = " selected";
				}else{
					$res["polje_selected"][$key_res] = "";
				}
			}
		}
		return $res;
	}
	/**
	 * Preuzimanje svih gradova
	 *
	 * @return Array(lid,lok_naziv,lok_parent,lok_ptt)
	 */
	function get_Mesta(){
		return $this->get_Lokacije(1);
	}
	/**
	 * Preuzimanje svih lok.opstina
	 *
	 * @return Array(lid,lok_naziv,lok_parent,lok_ptt)
	 */
	function get_LokOpstine(){
		return $this->get_Lokacije(2);
	}
	/**
	 * Preuzimanje svih naselja
	 *
	 * @return Array(lid,lok_naziv,lok_parent,lok_ptt)
	 */
	function get_Naselja(){
		return $this->get_Lokacije(3);
	}
	/**
	 * Preuzimanje svih lokacija odredjenog tipa
	 *
	 * @param tip lokacije
	 * @return Array(opstina_id,opstina_name,opstina_parent)
	 */
	function get_Lokacije($type,$lid=null){
		$ret = array();
		$q = "SELECT * FROM lokacije WHERE lok_naziv!='' AND lok_tip=$type ORDER BY lok_naziv";
		$res= $this->db->select2($q);
		if(count($res)>0){
			foreach($res as $key_res=>$val_res){
				$res['polje_id'][$key_res]=$val_res["lid"];
				$res['polje_ime'][$key_res]=$val_res["lok_naziv"];
				$res['polje_parent'][$key_res]=$val_res["lok_parent"];
				$res['polje_ptt'][$key_res]=$val_res["lok_ptt"];
				if($lid == $val_res["lid"]){
					$res["polje_selected"][$key_res] = " selected";
				}else{
					$res["polje_selected"][$key_res] = "";
				}
			}
		}
		return $res;
	}
	/**
	 * preuzimanje svih kampanja
	 *
	 * @return Array(kampanja_id,kampanja_name)
	 */
	function get_Kampanje($id=0){
		$ret = array();
		$q = "SELECT * FROM kampanje ORDER BY kampanja_start_date DESC";
		$res= $this->db->select2($q);
		if(count($res)>0){
			foreach($res as $key_res=>$val_res){
				$res['polje_id'][$key_res]=$val_res["kampanja_id"];
				$res['polje_ime'][$key_res]=$val_res["kampanja_naziv"];
				$res['polje_start'][$key_res]=$val_res["kampanja_start_date"];
				$res['polje_end'][$key_res]=$val_res["kampanja_end_date"];
				if($res['polje_id'][$key_res] == $id){
					$res['polje_selected'][$key_res] = " selected";
				}else{
					$res['polje_selected'][$key_res] = "";
				}
			}
		}
		return $res;
	}
	
	function get_Radnici($id=null,$akt=null,$group=null){
		$ret = array();
		$q = "SELECT radnik_id, radnik_ime, radnik_prezime FROM radnici WHERE 1 ";
		if ($akt!==null) {
			$q .= "AND radnik_akt=$akt ";
		}
		if ($group !== null) {
			$q .= " AND (0";
			foreach ($group as $groupid){
				$q .= " OR radnik_gr_id=$groupid";
			}
			$q .= ")";
		}
		$q.= "ORDER BY radnik_ime, radnik_prezime";
		$res= $this->db->select2($q);
		if(count($res)>0){
			foreach($res as $key_res=>$val_res){
				$res['polje_id'][$key_res]=$val_res["radnik_id"];
				$res['polje_ime'][$key_res]=$val_res["radnik_ime"];
				$res['polje_prezime'][$key_res]=$val_res["radnik_prezime"];
				if($val_res["radnik_id"] == $id){
					$res['polje_selected'][$key_res] = " selected";
				}else{
					$res['polje_selected'][$key_res] = "";
				}
			}
		}
		return $res;
	}
	function get_RadniciGrupe($group){
		$ret = array();
		$q = "SELECT * FROM radnici_grupe ORDER BY rad_grupa_name";
		$res = $this->db->select2($q);
		if ($res !== false) {
			foreach ($res as $key_res=>$val_res){
				$ret["polje_id"][$key_res] = $val_res["rad_grupa_id"];
				$ret["polje_ime"][$key_res] = $val_res["rad_grupa_name"];
				if ($val_res["rad_grupa_id"]==$group) {
					$ret["polje_selected"][$key_res] = " selected";
				}else{
					$ret["polje_selected"][$key_res] = "";
				}
			}
		}
		return $ret;
	}
	function get_Kategorije($id=null){
		$q = "SELECT * FROM kategorije ORDER BY kat_ime";
		$res = $this->db->select2($q);
		$ret = "";
		foreach ($res as $k=>$v){
			$ret["polje_id"][$k] = $v["kat_id"];
			$ret["polje_ime"][$k] = $v["kat_ime"];
			$ret["polje_ime_eng"][$k] = $v["kat_ime_eng"];
			if($id == $v["kat_id"]){
				$ret["polje_selected"][$k] = " selected";
			}else{
				$ret["polje_selected"][$k] = "";
			}
		}
		return $ret;
	}
	function get_Delatnosti($kat=null,$delnaz=null){
		
		$q = "SELECT d.*, dk.delkat_katid, k.kat_ime "
			."FROM delatnosti d, delatnosti_kategorije dk, kategorije k "
			."WHERE d.delatnost_id=dk.delkat_delid "
			."AND k.kat_id=dk.delkat_katid ";
		if(isset($kat)){
			$q .= "AND dk.delkat_katid=$kat ";
		}
		if(isset($delnaz)){
			$sort = "d.delatnost_id";
			if (strlen(trim($delnaz))>0) {
				$delnaz = trim($delnaz);
				if (preg_match('/^\d+$/',$delnaz)) {
					$q .= "AND d.delatnost_id=$delnaz ";
				}else{
					$q .= "AND (d.delatnost_ime LIKE '%$delnaz%' OR d.delatnost_ime_eng like '%$delnaz%') ";
				}
			}
			
			if(strlen(trim($delnaz))>0)
			$sort = "d.delatnost_ime";
		}else{
			$sort = "d.delatnost_ime";
		}
		$q .= "ORDER BY $sort";
		$ret="";
		
		$res = $this->db->select2($q);
		if($res[0]){
			foreach ($res as $k=>$row){
				$ret["polje_id"][$k] = $row["delatnost_id"];
				$ret["polje_ime"][$k] = $row["delatnost_ime"];
				$ret["polje_ime_eng"][$k] = $row["delatnost_ime_eng"];
				$ret["polje_kat"][$k] = $row["delkat_katid"];
				$ret["polje_kat_name"][$k] = $row["kat_ime"];
				if($delnaz == $row["delatnost_id"]){
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
			return $ret;
		}else{
			return false;
		}
	}
	function get_DelatnostiAll($delid){
		$res = $this->db->select2("SELECT * FROM delatnosti ORDER BY delatnost_ime");
		if ($res !== false) {
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["delatnost_id"];
				$ret["polje_ime"][$k] = $v["delatnost_ime"];
				$ret["polje_ime_eng"][$k] = $v["delatnost_ime_eng"];
				if ($v["delatnost_id"]==$delid) {
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		return $ret;
	}
	function get_DelatnostiFamilies($delid){
		//$grp = $this->db->getOne("SELECT id FROM delatnosti_srodne WHERE delatnost=$delid LIMIT 1");
		if ($delid>0) {
			$q = "SELECT delatnost_id, delatnost_ime "
				."FROM delatnosti, delatnosti_srodne "
				."WHERE delatnosti.delatnost_id=delatnosti_srodne.delatnost "
				."AND delatnosti_srodne.id=$delid "
				."ORDER BY delatnost_ime";
			$res = $this->db->select2($q);
			if ($res !== false) {
				foreach ($res as $k=>$v){
					$ret["polje_id"][$k] = $v["delatnost_id"];
					$ret["polje_ime"][$k] = $v["delatnost_ime"];
					$ret["polje_group"][$k] = $delid;
				}
			}
		}
		return $ret;
	}
	
	function get_CeneArtikl($cenid){
		$cena = $this->db->getRow("SELECT * FROM cene WHERE cena_id=$cenid LIMIT 1",true);
		if ($cena !== null) {
			$ret["art_id"] = $cena["cena_art_id"];
			list($ret["art_name"],$ret["art_group"]) = $this->db->getRow("SELECT art_name,art_grupa_id FROM artikli WHERE art_id=".$cena["cena_art_id"]." LIMIT 1");
			$ret["art_tip_id"] = $cena["cena_art_tip"];
			$ret["art_tip_name"] = $this->db->getOne("SELECT arttip_name FROM artikli_tipovi WHERE arttip_id=".$cena["cena_art_tip"]." LIMIT 1");
			$ret["art_boja_id"] = $cena["cena_art_boja"];
			list($ret["art_boja_name"],$ret["art_boja_code"]) = $this->db->getRow("SELECT art_boja_name,art_boja_code FROM artikli_boje WHERE art_boja_id=".$cena["cena_art_boja"]." LIMIT 1");
			$ret["art_mera"] = $cena["cena_art_mera"];
			$ret["art_jmere_id"] = $cena["cena_art_jed_mere"];
			list($ret["art_jmere_val"],$ret["art_jmere_sval"]) = $this->db->getRow("SELECT unit_value, unit_svalue FROM jedinice_mere WHERE unit_id=".$cena["cena_art_jed_mere"]." LIMIT 1");
			
			$fullname["name"] = $ret["art_name"];
			if ($ret["art_tip_id"]>0) {
				$fullname["tip"] = $ret["art_tip_name"];
			}
			if ($ret["art_boja_id"]>0) {
				$fullname["boja"] = $ret["art_boja_name"];
			}
			if ($ret["art_jmere_id"]>0) {
				$fullname["mera"] = $ret["art_mera"]."".$ret["art_jmere_sval"];
			}
			$ret["art_full_name"] = $fullname;
			$ret["price"] = $cena["cena_value"];
		}
		return $ret;
	}
	
	function get_CenePaket($paketid){
		require_once("artikli.class.php");
		$art = new artikli();
		$ret = $art->get_ArtikliPaketSadrzaj($paketid);
		return $ret;
	}
	
	function getOglas($komid,$kampanja){
		$q = "SELECT artikl, paket, kolicina "
			."FROM ugovori u, ugovori_stavke us "
			."WHERE u.id=us.ugovor_id "
			."AND us.kampanja=$kampanja "
			."AND us.komitent=$komid";
		$res = $this->db->select2($q);
		if ($res !== false) {
			$ret = array();
			foreach ($res as $k=>$row){
				$paket = $row["paket"]>0?true:false;
				$artikl = $row["artikl"];
				$kolicina = $row["kolicina"];
				
				if ($paket) {
					
				}else{
					$q = "SELECT a.art_name "
						."FROM cene c, artikli a "
						."WHERE c.cena_art_id=a.art_id "
						."AND a.art_grupa_id=1 "
						."AND c.cena_id=$artikl";
					$res1 = $this->db->getOne($q,true);
					if ($res1) {
						$ret[] = array(
							"artikl" => $res1,
							"kolicina" => $row["kolicina"]
						);
					}
				}
			}
			return $ret;
		}else{
			return false;
		}
	}
	
	function get_KomitentUgovoriList($komid){
		if ($komid<1) {
			return;
		}
		$ugo = $this->get_KomitentUgovori($komid);
		//print_rarray($ugo);
		if($ugo !== false){
			$komname = $this->db->getOne("SELECT komitent_name FROM komitenti WHERE komitent_id=$komid LIMIT 1");
			//echo $_SERVER['REQUEST_URI'];
			foreach ($ugo as $ugovor){
				$ugoids[] = $ugovor["id"];
				$ugobrs[] = $ugovor["broj"];
				$radnik[] = $ugovor["radnik"];
				$dates[]  = $ugovor["datum"];
				$storno[] = $ugovor["storno"]==1?"storno":"";
				$price[]  = $ugovor["cena"];
				$dug[]    = $ugovor["dug"];
				
				$a = "";
				foreach ($ugovor["artikl"] as $art){
					$a .= '<li title="'.$art["delid"].".".$art["delatnost"].'"><span class="cena">'.$art["price"].'</span>'.$art["name"].'</li>';
				}
				$artikli[] = $a;
			}
			$this->assign("komitent_id",$komid);
			$this->assign("komitent_name",$komname);
			$this->assign("ugoid",$ugoids);
			$this->assign("ugobroj",$ugobrs);
			$this->assign("radnik",$radnik);
			$this->assign("datum",$dates);
			$this->assign("cena",$price);
			$this->assign("dugovanje",$dug);
			$this->assign("artikli",$artikli);
			$this->assign("storno",$storno);
			//echo prepareNasaSlovaFOX($out);
			return $this->parseTemplate("komitenti/get_ugovor.tpl");
		}else{
			return false;
		}
	}
	function get_KomitentUgovori($komid){
		$ret = false;
		
		$q = "SELECT id, broj, iznos_bruto, datum, tip_ugovora, saradnik "
			."FROM ugovori "
			."WHERE komitent=$komid "
			."ORDER BY datum DESC";
		
		$res = $this->db->select2($q);
		if ($res !== false) {
			$ret = array();
			foreach ($res as $row){
				foreach ($row as $k=>$v){
					$$k = trim($v);
				}
				
				$radnici = $this->db->getRow("SELECT radnik_ime, radnik_prezime FROM radnici WHERE radnik_id=$saradnik");
				if ($radnici) {
					$radnik = $radnici[0]." ".$radnici[1];
				}else{
					$radnik = "-";
				}
				
				$otplaceno = (float) $this->db->getOne("SELECT SUM(iznos) FROM ugovori_otplate WHERE ugoid=$id");
				
				$ret[$id]["id"]		= $id;
				$ret[$id]["broj"]	= $broj;
				$ret[$id]["radnik"]	= $radnik;
				$ret[$id]["datum"]	= datetime2str($datum);
				$ret[$id]["cena"]	= number_format($iznos_bruto,2,",",".");
				$ret[$id]["dug"]		= number_format($iznos_bruto-$otplaceno,2,",",".");
				$ret[$id]["storno"]	= $tip_ugovora==5?"1":"0";
				
				$ret[$id]["artikl"]	= array();
				$q = "SELECT * FROM ugovori_stavke WHERE ugovor_id=$id ORDER BY iznos_bruto DESC";
				$stavke = $this->db->select2($q);
				if ($stavke !== false) {
					$i=0;
					
					foreach ($stavke as $i=>$row){
						$delid = $row["delatnost"];
						$delatnost = $this->db->getOne("SELECT delatnost_ime FROM delatnosti WHERE delatnost_id=$delid LIMIT 1");
						
						$ret[$id]["delnaz"] = $delatnost;
						$ret[$id]["delid"] = $delid;
						if ($row["paket"]>0) {
							require_once("artikli.class.php");
							$art = new artikli();
							$paket = $art->get_ArtikliPaketSadrzaj($row["artikl"]);
							$artname = $paket["name"];
						}else{
							$cena = $this->get_CeneArtikl($row["artikl"]);
							$artname = $cena["art_name"];
							if ($cena["art_tip_id"]>0) {
								$artname .= " - ".$cena["art_tip_name"];
							}
							if ($cena["art_boja_id"]>0) {
								$artname .= " - ".$cena["art_boja_code"];
							}
							if ($cena["art_jmere_id"]>0) {
								$artname .= " - ".$cena["art_mera"]."".$cena["art_jmere_sval"];
							}
						}
						
						$ret[$id]["artikl"][$i]["name"] = $artname;
						$ret[$id]["artikl"][$i]["price"] = number_format($row["iznos_bruto"],2,",",".");
						$ret[$id]["artikl"][$i]["delid"] = $delid;
						$ret[$id]["artikl"][$i]["delatnost"] = $delatnost;
					}
				}
			}
		}
		return $ret;
	}
	
	//-----------------------------------------------------------------------------------------
	
	function getFoxID($komid){
		$foxid = $this->db->getOne("SELECT fox FROM yapfox WHERE yap=$komid LIMIT 1");
		if (!$foxid) {
			$tst = $this->db->getOne("SELECT yap FROM yapfox WHERE fox=$komid LIMIT 1");
			if ($tst>0) {
				$foxid=false;
			}else{
				$foxid=$komid;
			}
		}
		return $foxid;
	}
	
	function VSON($data){
		$ret = false;
		$rows = explode("{!!}",$data);
		foreach ($rows as $k=>$v){
			$tmp = explode("=",$v,2);
			$name = trim($tmp[0]);
			$value = $tmp[1];
			if (preg_match('/\{!\}/',$value)) {
				$ret[$name] = explode("{!}",$value);
			}else{
				$ret[$name] = $value;
			}
		}
		
		return $ret;
	}

	function getCenovnik($time){
	
		$q = "SELECT cenovnik_id, cenovnik_start "
			."FROM cenovnici "
			."WHERE cenovnik_start<$time "
			."ORDER BY cenovnik_start DESC LIMIT 1";
		list($cenovnik_id,$cenovnik_date) = $this->db->getRow($q);
		
		$result=int2date($cenovnik_date)."{!}";
		
		if ($cenovnik_id>0) {
			$polja = $this->get_Cene($cenovnik_id);
				$this->assign("stavka_id",$polja["polje_id"]);
				$this->assign("stavka_name",$polja["polje_ime"]);
				$this->assign("stavka_artikl",$polja["polje_artikl"]);
				$this->assign("stavka_tip",$polja["polje_artikl_tip"]);
				$this->assign("stavka_boja",$polja["polje_artikl_boja"]);
				$this->assign("stavka_mera",$polja["polje_artikl_mera"]);
				$this->assign("stavka_jmere",$polja["polje_artikl_jmere"]);
				$this->assign("stavka_cena",$polja["polje_cena"]);
				
			$polja = $this->get_Paketi($cenovnik_id,$time);
				$this->assign("pack_id",$polja["polje_id"]);
				$this->assign("pack_name",$polja["polje_ime"]);
				$this->assign("pack_cena",$polja["polje_cena"]);
				$this->assign("pack_start_date",$polja["polje_start_date"]);
				$this->assign("pack_end_date",$polja["polje_end_date"]);
				$this->assign("pack_sadrzaj",$polja["polje_sadrzaj"]);
				$this->assign("pack_sadrzaj_desc",$polja["polje_sadrzaj_desc"]);
				
			$content = $this->parseTemplate("ugovori/stavkeCene.tpl");
			
			return $result."$cenovnik_id{!}$content";
		}else{
			return "0{!}Ne postoji cenovnik pre ".int2date($time).". god.";
		}
	}
	
	function get_Cene($cenovnik=null,$cid=null){
		$ret = array();
		if($cenovnik == null){
			$now = time();
			$q = "SELECT cenovnik_id FROM cenovnici WHERE cenovnik_start<$now ORDER BY cenovnik_start ASC LIMIT 1";
			$cenovnik = $this->db->getOne($q);
		}
		
		$q = "SELECT c.*, art_name, art_desc "
			."FROM artikli a, cene c, cenovnici cen "
			."WHERE c.cena_art_id=a.art_id "
			."AND c.cena_cenovnik=cen.cenovnik_id "
			."AND cen.cenovnik_id=$cenovnik ";
		if ($cid !== null) {
			$q .= "AND c.cena_id=$cid ";
		}
		$q .= "ORDER BY art_name";
		$res = $this->db->select2($q);
		if($res !== false){
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["cena_id"];
				$stavka_name = $v["art_name"];
				if ($v["cena_art_tip"]>0) {
					$tip_name = $this->db->getOne("SELECT arttip_name FROM artikli_tipovi WHERE arttip_id=".$v["cena_art_tip"]." LIMIT 1");
					$stavka_name .= " - $tip_name";
				}
				if ($v["cena_art_boja"]>0) {
					list($boja_name,$boja_code) = $this->db->getRow("SELECT art_boja_name, art_boja_code FROM artikli_boje WHERE art_boja_id=".$v["cena_art_boja"]." LIMIT 1");
					$stavka_name .= " / $boja_code";
				}
				if ($v["cena_art_mera"]>0) {
					$jedmere = $this->db->getOne("SELECT unit_svalue FROM jedinice_mere WHERE unit_id=".$v["cena_art_jed_mere"]." LIMIT 1");
					$stavka_name .= " - ".$v["cena_art_mera"].$jedmere;
				}
				$ret["polje_ime"][$k] = $stavka_name;
				$ret["polje_artikl"][$k] = $v["cena_art_id"];
				$ret["polje_artikl_tip"][$k] = $v["cena_art_tip"];
				$ret["polje_artikl_boja"][$k] = $v["cena_art_boja"];
				$ret["polje_artikl_mera"][$k] = $v["cena_art_mera"];
				$ret["polje_artikl_jmere"][$k] = $v["cena_art_jed_mere"];
				$ret["polje_cena"][$k] = $v["cena_value"];
			}
		}
		return $ret;
	}

	function get_Paketi($cenovnik,$time=null){
		$ret = array();
		$q = "SELECT ap.* "
			."FROM artikli_paketi ap, cenovnici c "
			."WHERE ap.paket_start>=c.cenovnik_start ";
		if($time>0){
			$q .= "AND (ap.paket_start<=$time AND ap.paket_end>=$time) ";
		}
			
		$q .= "AND c.cenovnik_id=$cenovnik "
			."ORDER BY paket_start DESC, paket_end DESC, paketname ASC";
		$res = $this->db->select2($q);
		if ($res !== false) {
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["paketid"];
				$ret["polje_ime"][$k] = $v["paketname"];
				$ret["polje_start"][$k] = $v["paket_start"];
				$ret["polje_end"][$k] = $v["paket_end"];
				$ret["polje_start_date"][$k] = date($this->getFromConfig("short_date"),$v["paket_start"]);
				$ret["polje_end_date"][$k] = date($this->getFromConfig("short_date"),$v["paket_end"]);
				$ret["polje_cena"][$k] = $v["cena"];
				$ret["polje_desc"][$k] = $v["opis"];
				
				$q = "SELECT cena_art_id, art_name, cena_art_tip, arttip_name, "
							."cena_art_boja, art_boja_name, art_boja_code, cena_art_mera, unit_svalue, "
							."apa.cena, cena_value, popust "
					."FROM artikli a, artikli_paketi ap, artikli_paketi_artikli apa, "
							."artikli_tipovi at, artikli_boje ab, cene c, jedinice_mere jm "
					."WHERE ap.paketid=apa.paket "
							."AND apa.cena=c.cena_id "
							."AND cena_art_id=a.art_id "
							."AND cena_art_tip=at.arttip_id "
							."AND cena_art_boja=ab.art_boja_id "
							."AND cena_art_jed_mere=jm.unit_id "
							."AND ap.paketid=".$v["paketid"];
				$res_s = $this->db->select2($q);
				
				$sadrzaj=$sadrzaj_desc="";
				$row_delim="\n";
				$cel_delim=";";
				if ($res_s !== false) {
					foreach ($res_s as $ks=>$vs){
						$sadrzaj .= $row_delim.trim($vs["cena"]).$cel_delim.trim($vs["popust"]);
						
						$art = $vs["art_name"];
						if ($vs["cena_art_tip"]>0) {
							$art .= " - ".$vs["arttip_name"];
						}
						if ($vs["cena_art_boja"]>0) {
							$art .= " - ".$vs["art_boja_name"];
						}
						if ($vs["cena_art_jed_mere"]>0) {
							$art .= " - ".$vs["cena_art_mera"]."".strtolower($vs["unit_svalue"]).".";
						}
						
						$sadrzaj_desc .= $row_delim.$art.$cel_delim.trim($vs["cena_value"]).$cel_delim.trim($vs["popust"]);
					}
					
					$sadrzaj = substr($sadrzaj,strlen($row_delim));
					$sadrzaj_desc = substr($sadrzaj_desc,strlen($row_delim));
				}
				$ret["polje_sadrzaj"][$k] = $sadrzaj;
				$ret["polje_sadrzaj_desc"][$k] = $sadrzaj_desc;
			}
		}
		return $ret;
	}
}


/**
 * Prazna klasa za dinamicko instanciranje novih klasa
 *
 */
class voomy{
	function voomy(){
		
	}
}

?>